<?php

namespace app\common\model;

use app\admin\model\shopro\store\News;
use think\Exception;

class ShoproStoreNews extends News
{
    public static function getNewsList($params, $field = null)
    {
        extract($params);

        $where = [];

        if (isset($status) && in_array($status, [0, 1])) {
            $where['status'] = $status;
        } else {
            $where['status'] = 1;
        }

        if (!empty($store_id)) {
            $where['shopro_store_id'] = $store_id;
        }

        if (isset($title) && $title !== '') {
            $where['title'] = ['like', "%$title%"];
        }

        $newsQeury = self::where($where)->with(['store' => function ($query) {
            return $query->field('id,name,desc,images,openweeks');
        }])->order('id', 'desc');

        if ($field) {
            $newsQeury = $newsQeury->field($field);
        }

        $storeNews = $newsQeury->paginate($per_page ?? 10);

        $news = $storeNews->items();
        foreach ($news as $key => &$item) {
            $item['createtime_str'] = date('Y.m.d', $item['createtime']);
            $item['updatetime_str'] = date('Y.m.d', $item['createtime']);
        }
        $storeNews->data = $news;

        return $storeNews;
    }

    public static function getNewsDetail($id)
    {
        $detail = self::where('id', $id)->with(['store' => function ($query) {
            return $query->field('id,name,desc,images,openweeks');
        }])->find();

        if (!$detail || $detail->status === 0) {
            throw new Exception('请求异常，请刷新重试');
        }

        $detail['createtime_str'] = date('Y.m.d', $detail['createtime']);
        $detail['updatetime_str'] = date('Y.m.d', $detail['createtime']);

        return $detail;
    }
}
